#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <unistd.h>

#include <sys/types.h>
#include <signal.h>

static int open_route(char *pname, FILE **pf)
{
	char route_cmd[256] = {0};
	if(NULL != pname && sizeof(route_cmd) - 56 >= strlen(pname))
	{
		bzero(route_cmd, sizeof(route_cmd));
		snprintf(route_cmd, sizeof(route_cmd), "ps | grep '%s' | grep -v 'grep'", pname);
		*pf = NULL;
		*pf = popen(route_cmd, "r");
		if(NULL != *pf)
		{
			return 0;
		}
	}
	return -1;
}

static void kill_pid_by_name(char *pname)
{
	pid_t pid = 0;

	FILE *pf = NULL;
	char recv_buf[256] = {0};

	if(0 == open_route(pname, &pf))
	{
		fread(recv_buf, sizeof(recv_buf), 1, pf);
		fclose(pf);

		if(0 < strlen(recv_buf))
		{
			if('0' <= recv_buf[2] && '9' >= recv_buf[2])
			{
				pid = (pid_t)atoi(recv_buf);
			}
		}
	}

	if(0 == pid)
	{
		printf("can't kill '%s': No such process\n", pname);
	}
	else
	{
		kill(pid, 9);
	}
}

int main(int argc, char **argv)
{
	kill_pid_by_name("/usr/share/ipcam/shell/startup.sh");
	kill_pid_by_name("/usr/share/ipcam/app");

	sleep(1);

	system("rmmod watchdog");

	return 0;
}